package com.xiaoyao.novel.service;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.xiaoyao.novel.common.Pagin;
import com.xiaoyao.novel.dao.BaseDao;

/**
 * T 为要操作的 bean 类
 * 
 * @author 旷明爱
 * @date 2013-8-19 下午03:33:33
 */
public class BaseService<T> {
	protected Logger logger = Logger.getLogger(this.getClass());
	private BaseDao<T> baseDao = null;

	protected BaseService(BaseDao<T> baseDao) {
		this.baseDao = baseDao;
	}

	// /////////////////////////

	public void insert(T object) {
		try {
			baseDao.insert(object);
		} catch (SQLException e) {
			// e.printStackTrace();
			logger.error("插入失败:" + e);
		}
	}

	public void insert(List<T> list) {
		try {
			baseDao.insert(list);
		} catch (SQLException e) {
			// e.printStackTrace();
			logger.error("插入失败:" + e);
		}
	}

	public void delete(Object id) {
		try {
			baseDao.delete(id);
		} catch (Exception e) {
			logger.error("删除失败:"+e);
		}
	}

	public void update(T object) {
		try {
			baseDao.update(object);
		} catch (Exception e) {
			logger.error("修改失败:"+e);
		}
	}

	public T getById(Object id) {
		T ret = null;
		try {
			ret = baseDao.getById(id);
		} catch (Exception e) {
			logger.error(e);
		}
		return ret;
	}

	// ////

	/**
	 * 返回键值对形式的数据
	 * 
	 * @param pagin
	 * @return @
	 */
	public List<Map<String, Object>> searchMap(Pagin pagin) {
		List<Map<String, Object>> list = null;
		try { 
			list = baseDao.searchMap(pagin);
			pagin.setList(list);
		} catch (Exception e) {
			logger.error(e);
		}
		return list;
	}

	public List<T> search(Pagin pagin) {
		List<T> list = null;
		try { 
			pagin.setRowCount(searchCount(pagin));
			list = baseDao.search(pagin);
			pagin.setList(list);
		} catch (Exception e) {
			logger.error(e);
		}
		return list;
	}

	public int searchCount(Pagin pagin) {
		int count = 0;
		try { 
			count = baseDao.searchCount(pagin);
			pagin.setRowCount(count);
		} catch (Exception e) {
			logger.error(e);
		}
		return count;
	}

	//
	public List<T> getAll() {
		List<T> list = null;
		try {
			list = baseDao.getAll();
		} catch (Exception e) {
			logger.error(e);
		}
		return list;
	}

	public void deleteAll() {
		try {
			baseDao.deleteAll();
		} catch (Exception e) {
			logger.error(e);
		}
	}
}
